<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
<meta name="viewport"
      content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">

    <meta name="author" content="ZhangPing">





<title>Android视频缓存实现 | ZhangPing&#39;s Blog</title>



    <link rel="icon" href="/favicon.ico">




    <!-- stylesheets list from _config.yml -->
    
    <link rel="stylesheet" href="/css/style.css">
    



    <!-- scripts list from _config.yml -->
    
    <script src="/js/script.js"></script>
    
    <script src="/js/tocbot.min.js"></script>
    



    
    
        
    


<meta name="generator" content="Hexo 4.2.0"></head>
<body>
    <div class="wrapper">
        <header>
    <nav class="navbar">
        <div class="container">
            <div class="navbar-header header-logo"><a href="/">ZhangPing&#39;s Blog</a></div>
            <div class="menu navbar-right">
                
                    <a class="menu-item" href="/archives">Posts</a>
                
                    <a class="menu-item" href="/category">Categories</a>
                
                    <a class="menu-item" href="/tag">Tags</a>
                
                    <a class="menu-item" href="/about">About</a>
                
                <input id="switch_default" type="checkbox" class="switch_default">
                <label for="switch_default" class="toggleBtn"></label>
            </div>
        </div>
    </nav>

    
    <nav class="navbar-mobile" id="nav-mobile">
        <div class="container">
            <div class="navbar-header">
                <div>
                    <a href="/">ZhangPing&#39;s Blog</a><a id="mobile-toggle-theme">·&nbsp;Light</a>
                </div>
                <div class="menu-toggle" onclick="mobileBtn()">&#9776; Menu</div>
            </div>
            <div class="menu" id="mobile-menu">
                
                    <a class="menu-item" href="/archives">Posts</a>
                
                    <a class="menu-item" href="/category">Categories</a>
                
                    <a class="menu-item" href="/tag">Tags</a>
                
                    <a class="menu-item" href="/about">About</a>
                
            </div>
        </div>
    </nav>

</header>
<script>
    var mobileBtn = function f() {
        var toggleMenu = document.getElementsByClassName("menu-toggle")[0];
        var mobileMenu = document.getElementById("mobile-menu");
        if(toggleMenu.classList.contains("active")){
           toggleMenu.classList.remove("active")
            mobileMenu.classList.remove("active")
        }else{
            toggleMenu.classList.add("active")
            mobileMenu.classList.add("active")
        }
    }
</script>
        <div class="main">
            <div class="container">
    
    
        <div class="post-toc">
    <div class="tocbot-list">
    </div>
    <div class="tocbot-list-menu">
        <a class="tocbot-toc-expand" onclick="expand_toc()">Expand all</a>
        <a onclick="go_top()">Back to top</a>
        <a onclick="go_bottom()">Go to bottom</a>
    </div>
</div>

<script>
    document.ready(
        function () {
            tocbot.init({
                tocSelector: '.tocbot-list',
                contentSelector: '.post-content',
                headingSelector: 'h1, h2, h3, h4, h5',
                collapseDepth: 1,
                orderedList: false,
                scrollSmooth: true,
            })
        }
    )

    function expand_toc() {
        var b = document.querySelector(".tocbot-toc-expand");
        tocbot.init({
            tocSelector: '.tocbot-list',
            contentSelector: '.post-content',
            headingSelector: 'h1, h2, h3, h4, h5',
            collapseDepth: 6,
            orderedList: false,
            scrollSmooth: true,
        });
        b.setAttribute("onclick", "collapse_toc()");
        b.innerHTML = "Collapse all"
    }

    function collapse_toc() {
        var b = document.querySelector(".tocbot-toc-expand");
        tocbot.init({
            tocSelector: '.tocbot-list',
            contentSelector: '.post-content',
            headingSelector: 'h1, h2, h3, h4, h5',
            collapseDepth: 1,
            orderedList: false,
            scrollSmooth: true,
        });
        b.setAttribute("onclick", "expand_toc()");
        b.innerHTML = "Expand all"
    }

    function go_top() {
        window.scrollTo(0, 0);
    }

    function go_bottom() {
        window.scrollTo(0, document.body.scrollHeight);
    }

</script>
    

    
    <article class="post-wrap">
        <header class="post-header">
            <h1 class="post-title">Android视频缓存实现</h1>
            
                <div class="post-meta">
                    
                        Author: <a itemprop="author" rel="author" href="/">ZhangPing</a>
                    

                    
                        <span class="post-time">
                        Date: <a href="#">May 9, 2017&nbsp;&nbsp;20:25:00</a>
                        </span>
                    
                    
                        <span class="post-category">
                    Category:
                            
                                <a href="/categories/Android-%E7%BB%84%E4%BB%B6/">Android-组件</a>
                            
                        </span>
                    
                </div>
            
        </header>

        <div class="post-content">
            <p>公司是做线上教育的，在整个服务器的成本中，我们发现存储的成本很低约占总支出的5%，流量成本大约占95%，所以流量缓存势在必行。经过调研在github上找到了一个很不错的第三方缓存库（<a href="https://github.com/danikula/AndroidVideoCache）" target="_blank" rel="noopener">https://github.com/danikula/AndroidVideoCache）</a> ，下面把他的用法做一个介绍。</p>
<h4 id="1-为什么要做视频缓存"><a href="#1-为什么要做视频缓存" class="headerlink" title="1.为什么要做视频缓存"></a>1.为什么要做视频缓存</h4><p>因为在播放流媒体视频时多次下载视频没有任何意义，AndroidVideoCache只需要通过很少的代码为您的VideoView / MediaPlayer，ExoPlayer或任何其他播放器添加缓存支持！</p>
<h4 id="2-该视频缓存库的特点"><a href="#2-该视频缓存库的特点" class="headerlink" title="2.该视频缓存库的特点"></a>2.该视频缓存库的特点</h4><ul>
<li>流媒体缓存到磁盘; </li>
<li>可以使用缓存资源进行离线播放; </li>
<li>部分装载 缓存限制（最大缓存大小，最大文件数）; </li>
<li>同一网址的多个客户端。</li>
</ul>
<p>注意：AndroidVideoCache只能播放地址是url的媒体文件，它不支持任何流技术，如DASH，SmoothStreaming，HLS。</p>
<h4 id="3-开始使用"><a href="#3-开始使用" class="headerlink" title="3.开始使用"></a>3.开始使用</h4><ul>
<li>首先添加依赖：</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">dependencies &#123;</span><br><span class="line">    compile <span class="string">'com.danikula:videocache:2.7.0'</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>使用代理的url代替原始网址添加缓存：</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onCreate</span><span class="params">(Bundle savedInstanceState)</span> </span>&#123;</span><br><span class="line"><span class="keyword">super</span>.onCreate(savedInstanceState);</span><br><span class="line"></span><br><span class="line">    HttpProxyCacheServer proxy = getProxy();</span><br><span class="line">    String proxyUrl = proxy.getProxyUrl(VIDEO_URL);</span><br><span class="line">    videoView.setVideoPath(proxyUrl);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> HttpProxyCacheServer <span class="title">getProxy</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">// should return single instance of HttpProxyCacheServer shared for whole app.</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>为了保证正常工作，整个应用程序应该使用HttpProxyCacheServer的单例。<br>例如，您可以在Application中存储共享代理：</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">App</span> <span class="keyword">extends</span> <span class="title">Application</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> HttpProxyCacheServer proxy;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> HttpProxyCacheServer <span class="title">getProxy</span><span class="params">(Context context)</span> </span>&#123;</span><br><span class="line">        App app = (App) context.getApplicationContext();</span><br><span class="line">        <span class="keyword">return</span> app.proxy == <span class="keyword">null</span> ? (app.proxy = app.newProxy()) : app.proxy;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> HttpProxyCacheServer <span class="title">newProxy</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> HttpProxyCacheServer(<span class="keyword">this</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>或使用简单的工厂模式，更好的方法是使用像Dagger这样的依赖注入。</p>
<h4 id="4-方法"><a href="#4-方法" class="headerlink" title="4.方法"></a>4.方法</h4><ul>
<li>磁盘缓存限制</li>
</ul>
<p>HttpProxyCacheServer 默认缓存空间为512M，你可以通过下面的方法修改缓存大小：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> HttpProxyCacheServer <span class="title">newProxy</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> HttpProxyCacheServer.Builder(<span class="keyword">this</span>)</span><br><span class="line">            .maxCacheSize(<span class="number">1024</span> * <span class="number">1024</span> * <span class="number">1024</span>)       <span class="comment">// 1 Gb for cache</span></span><br><span class="line">            .build();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>或者可以限制缓存中的文件总数：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> HttpProxyCacheServer <span class="title">newProxy</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> HttpProxyCacheServer.Builder(<span class="keyword">this</span>)</span><br><span class="line">            .maxCacheFilesCount(<span class="number">20</span>)</span><br><span class="line">            .build();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>甚至实现您自己的DiskUsage策略：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> HttpProxyCacheServer <span class="title">newProxy</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> HttpProxyCacheServer.Builder(<span class="keyword">this</span>)</span><br><span class="line">            .diskUsage(<span class="keyword">new</span> MyCoolDiskUsageStrategy())</span><br><span class="line">            .build();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>监听缓存进度<br>使用 HttpProxyCacheServer.registerCacheListener（CacheListener listener）方法设置监听。<br>在回调 onCacheAvailable（File cacheFile，String url，int percentsAvailable）中获取缓存进度。<br>不要忘记在 HttpProxyCacheServer.unregisterCacheListener（CacheListener listener）方法的帮助下取消订阅监听器，以避免内存泄漏。<br>使用 HttpProxyCacheServer.isCached（String url）方法来检查url的内容是否完全缓存到文件。</li>
</ul>
<p>有关详细信息，请参阅示例应用程序。</p>
<ul>
<li>为缓存文件提供名称<br>默认情况下，AndroidVideoCache使用视频网址的MD5作为文件名。 但是在某些情况下，url不稳定，并且可以包含一些生成的部分（例如会话令牌）。 在这种情况下，缓存机制将被破坏。 要修复它，你必须提供自己的FileNameGenerator：</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyFileNameGenerator</span> <span class="keyword">implements</span> <span class="title">FileNameGenerator</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Urls contain mutable parts (parameter 'sessionToken') and stable video's id (parameter 'videoId').</span></span><br><span class="line">    <span class="comment">// e. g. http://example.com?videoId=abcqaz&amp;sessionToken=xyz987</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">generate</span><span class="params">(String url)</span> </span>&#123;</span><br><span class="line">        Uri uri = Uri.parse(url);</span><br><span class="line">        String videoId = uri.getQueryParameter(<span class="string">"videoId"</span>);</span><br><span class="line">        <span class="keyword">return</span> videoId + <span class="string">".mp4"</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">...</span><br><span class="line">HttpProxyCacheServer proxy = HttpProxyCacheServer.Builder(context)</span><br><span class="line">    .fileNameGenerator(<span class="keyword">new</span> MyFileNameGenerator())</span><br><span class="line">    .build()</span><br></pre></td></tr></table></figure>

<ul>
<li><p>使用exoPlayer<br>可以使用exoPlayer中使用AndroidVideoCache。 请参阅exoPlayer分支中的示例应用程序。 注意exoPlayer也支持缓存。</p>
</li>
<li><p>已知问题<br>在某些情况下，客户端无法连接到本地代理服务器（’Error pinging server’ error）。 可能是以前的错误。 注意在这种情况下，视频可以正常播放，但没有缓存。</p>
</li>
</ul>
<p><em>文末再次附上链接：<a href="https://github.com/danikula/AndroidVideoCache" target="_blank" rel="noopener">https://github.com/danikula/AndroidVideoCache</a></em></p>

        </div>

        
            <section class="post-copyright">
                
                    <p class="copyright-item">
                        <span>Author:</span>
                        <span>ZhangPing</span>
                    </p>
                
                
                    <p class="copyright-item">
                        <span>Permalink:</span>
                        <span><a href="https://zhangpingv5.gitee.io/2017/05/09/Android%E8%A7%86%E9%A2%91%E7%BC%93%E5%AD%98%E6%94%AF%E6%8C%81%E5%BA%93/">https://zhangpingv5.gitee.io/2017/05/09/Android%E8%A7%86%E9%A2%91%E7%BC%93%E5%AD%98%E6%94%AF%E6%8C%81%E5%BA%93/</a></span>
                    </p>
                
                
                    <p class="copyright-item">
                        <span>License:</span>
                        <span>转载请注明出处</span>
                    </p>
                
                
                     <p class="copyright-item">
                         <span>Slogan:</span>
                         <span>Self-descipline grants me freedom.</span>
                     </p>
                

            </section>
        
        <section class="post-tags">
            <div>
                <span>Tag(s):</span>
                <span class="tag">
                    
                    
                        <a href="/tags/%E8%A7%86%E9%A2%91/"># 视频</a>
                    
                        
                </span>
            </div>
            <div>
                <a href="javascript:window.history.back();">back</a>
                <span>· </span>
                <a href="/">home</a>
            </div>
        </section>
        <section class="post-nav">
            
                <a class="prev" rel="prev" href="/2017/09/20/ARouter%E8%B7%AF%E7%94%B1%E6%A1%86%E6%9E%B6%E4%BB%8B%E7%BB%8D/">ARouter路由框架介绍</a>
            
            
            <a class="next" rel="next" href="/2017/05/07/AAPTerr/">AAPTerr ERROR Unable to open PNG file</a>
            
        </section>


    </article>
</div>

        </div>
        <footer id="footer" class="footer">
    <div class="copyright">
        <span>© ZhangPing | Powered by <a href="https://hexo.io" target="_blank">Hexo</a> & <a href="https://github.com/Siricee/hexo-theme-Chic" target="_blank">Chic</a></span>
    </div>
</footer>

    </div>
</body>
</html>
